<template>
  <div class="reg-step__2">
    <div class="reg-title">
      <div><span class="big">2</span>完善信息</div>
      <div>简单介绍一下你自己～</div>
    </div>
    <div class="wrapper-form">
      <a-form :label-col="{ span: 6 }" size="large" ref="formRef" :rules="rules" :model="formData">
        <a-form-item name="avatarUrl" class="avatar-form-item">
          <a-upload
            v-model:file-list="formData.avatarUrl"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="onAction()"
            :before-upload="onBeforeUpload"
            @change="handleChange"
            :headers="httpHeaders"
            method="post"
            :maxCount="1"
            accept=".png, .jpg, .jpeg"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
            <div v-else class="full">
              <loading-outlined v-if="loading"></loading-outlined>
              <img src="~@/assets/images/upload-zhan-wei@2x.png" class="default-avatar" alt="" v-else />
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item label="姓名" name="name">
          <a-input v-model:value="formData.name" size="large" placeholder="请输入您的真实姓名"></a-input>
        </a-form-item>
        <a-form-item label="性别" name="genderEnum">
          <a-radio-group v-model:value="formData.genderEnum">
            <a-radio value="male">男</a-radio>
            <a-radio value="female">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="出生日期" name="dateOfBirth">
          <a-date-picker
            v-model:value="formData.dateOfBirth"
            format="YYYY/MM/DD"
            size="large"
            style="width: 100%"
            placeholder="请选择"
            :disabled-date="disabledUserAgeDate"
          />
        </a-form-item>
        <a-form-item label="参加工作日期" name="workStartYear">
          <a-date-picker
            v-model:value="formData.workStartYear"
            picker="year"
            size="large"
            style="width: 100%"
            placeholder="请选择"
            :disabled-date="disabledDateWorkStartYear"
          />
        </a-form-item>
        <a-form-item label="现居住省份" name="currentAreacode">
          <a-select
            :options="_provinceList"
            v-model:value="formData.currentAreacode"
            size="large"
            :fieldNames="{ label: 'name', value: 'id', options: 'options' }"
            placeholder="请选择"
            @change="AreaChange"
            allowClear
          >
          </a-select>
        </a-form-item>
        <a-form-item label="现居住城市" name="currentStreetCode" v-if="formData.currentAreacode">
          <a-select
            :options="_cityList"
            v-model:value="formData.currentStreetCode"
            size="large"
            :fieldNames="{ label: 'name', value: 'id', options: 'options' }"
            placeholder="请选择"
            allowClear
          >
          </a-select>
        </a-form-item>
        <a-form-item label="常住地址" name="detailedLocation">
          <a-input
            size="large"
            v-model:value="formData.detailedLocation"
            placeholder="请输入"
            :maxlength="100"
          ></a-input>
        </a-form-item>
        <a-form-item label="当前薪资" name="salary">
          <CurrentSalaryInput v-model:value="formData.salary" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input size="large" v-model:value="formData.email" placeholder="请输入"></a-input>
        </a-form-item>
        <a-form-item label="微信" name="wechat">
          <a-input size="large" v-model:value="formData.wechat" placeholder="请输入"></a-input>
        </a-form-item>
      </a-form>
      <div class="btn-box">
        <a-button type="primary" @click="onBackClick">上一步</a-button>
        <a-button type="primary" @click="onNextClick">下一步</a-button>
      </div>
    </div>
  </div>
</template>
<script>
import CommonService from '@/api/common';
import CurrentSalaryInput from './CurrentSalaryInput.vue';
import UserService from '@/api/user';
import { message } from 'ant-design-vue';
import { fileLt5M, getBase64 } from '@/utils/util';
import { LoadingOutlined } from '@ant-design/icons-vue';
import { step2Rules as rules } from '../util';
import { disabledUserAgeDate, disabledDateWorkStartYear } from '@/utils/util';
import dayjs from 'dayjs';
import { Storage } from '@/utils/Storage';
import { useUserStore } from '@/store/user';
import { toRaw } from 'vue';
export default {
  components: {
    CurrentSalaryInput,
    LoadingOutlined,
  },
  emits: ['on-next', 'on-last'],
  data() {
    // const dateOfBirth = dayjs('1995-01-01', 'YYYY-MM-DD');
    return {
      formData: {
        genderEnum: 'female',
        dateOfBirth: dayjs('1995-01-01', 'YYYY/MM/DD'),
        workStartYear: null,
        currentAreacode: null,
        currentStreetCode: null,
        avatarUrl: [],
        detailedLocation: '',
        // detailedLocation: {
        //   address: undefined,
        //   lng: 0,
        //   lat: 0,
        //   city: '',
        // },
        houseNumber: '',
        salary: {
          salary: 10,
          salaryMonth: 12,
        },
        name: '',
        email: '',
        wechat: '',
      },
      areaList: [],
      StreetList: [],
      loading: false,
      imageUrl: '',
      httpHeaders: getHeaders(),
      rules,
      Register_1: Storage.get('Register_1'),
      userStore: useUserStore(),
    };
  },
  computed: {
    _provinceList() {
      return this.areaList?.filter((t) => t.level === 1);
    },
    _cityList() {
      return this.areaList?.filter((t) => t.parentId === this.formData?.currentAreacode);
    },
  },
  methods: {
    disabledUserAgeDate,
    disabledDateWorkStartYear,
    async onNextClick() {
      try {
        await this.$refs.formRef?.validate();
        //正常注册头像url
        const Url =
          this.formData?.avatarUrl
            ?.map((t) => t?.response?.data?.minioName)
            ?.filter((t) => t)
            ?.join(',') || 'empty.png';
        //上一步回显url
        const changUrl = this.formData?.avatarUrl
          ?.map((t) => t?.response?.data?.minioName)
          ?.filter((t) => t)
          ?.join(',');

        let editUrl = null;
        if (this.Register_1) {
          editUrl = toRaw(this.formData?.avatarUrl[0].url) || changUrl;
        }
        const params = {
          ...this.formData,
          avatarUrl: this.Register_1 ? editUrl : Url,
          salaryNum: this.formData?.salary?.salaryMonth || '',
          currentSalary: this.formData?.salary?.salary || '',
          dateOfBirth: this.formData.dateOfBirth?.format('YYYY-MM-DD') || '',
          workStartYear: this.formData.workStartYear?.format('YYYY') || '',
          // detailedLocation: this.formData.detailedLocation?.address || '',
          salary: null,
        };
        const resp = await UserService.improveSeekerInfo(params);
        if (resp.code === 200) {
          Storage.remove('Register_1');
          this.$emit('on-next', 2);
        } else {
          message.error(resp?.msg || '操作失败');
        }
      } catch (error) {
        console.log(error);
      }
    },
    handleChange(info) {
      if (!info.file?.status) {
        this.loading = false;
        this.imageUrl = null;
        return;
      }
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, (base64Url) => {
          if (base64Url.startsWith('data:image/')) {
            this.imageUrl = base64Url;
          } else {
            this.imageUrl = null;
          }
          this.loading = false;
        });
      }
      if (info.file.status === 'error') {
        this.loading = false;
        message.error('上传失败，请重试');
      }
    },
    onBeforeUpload(file) {
      const isLt = fileLt5M(file);
      if (!isLt) {
        message.error('图片需小于5M，请重新上传');
      }
      return isLt;
    },
    onAction() {
      const url = '/api/seeker-web/v1/uploadImage';
      return url;
    },
    async selectAreaListFromRedis() {
      try {
        const resp = await CommonService.selectAreaListFromRedis();
        if (resp.code === 200) {
          this.areaList = resp.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    async selectStreetListByAreaId(pid) {
      try {
        const resp = await CommonService.selectStreetListByAreaId(pid);
        if (resp.code === 200) {
          this.StreetList = resp.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    AreaChange(val) {
      this.formData.currentStreetCode = null;
      // if (val) {
      //   this.selectStreetListByAreaId(val);
      // }
    },
    onBackClick() {
      Storage.set('Register_0', true);
      this.$emit('on-next', 0);
    },
    async selectSeekerImprove() {
      try {
        const resp = await UserService.selectSeekerImprove();
        if (resp.code === 200) {
          const data = resp.data.seekerBO;
          this.formData = Object.assign(this.formData, data);

          // this.selectStreetListByAreaId(data.currentAreacode);
          this.formData.dateOfBirth = data?.dateOfBirth
            ? dayjs(data.dateOfBirth, 'YYYY/MM/DD')
            : dayjs('1995-01-01', 'YYYY/MM/DD');
          this.formData.workStartYear = dayjs(`${data.workStartYear}`);

          this.formData.salary.salary = data?.currentSalary || 0;
          this.formData.salary.salaryMonth = data?.salaryNum || 0;
          this.formData.avatarUrl = [
            { name: data?.avatarUrl, status: 'done', thumbUrl: data?.avatarPreviewUrl, url: data?.avatarUrl },
          ];
          this.imageUrl = data?.avatarPreviewUrl;

          this.userStore.setUserInfo(data);
        }
      } catch (error) {
        console.log(error);
      }
    },
  },
  mounted() {
    this.selectAreaListFromRedis();
    if (this.Register_1) {
      //返回上一步
      this.selectSeekerImprove();
    }
  },
};
</script>

<style lang="scss" scoped>
.reg-step__2 {
  box-sizing: border-box;
  padding: 0 302px 103px 278px;
  .avatar-form-item {
    :deep(.ant-form-item-explain) {
      text-align: center;
    }
  }
  :deep(.salary-input) {
    margin-bottom: 30px;
    .tips {
      color: #9696a4;
    }
  }

  .avatar-uploader {
    margin: 0 auto;
    margin-top: 16px;
    text-align: center;
    .full {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      .default-avatar {
        width: 100%;
        height: 100%;
      }
    }
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
    :deep(.ant-upload) {
      &.ant-upload-select-picture-card {
        width: 78px;
        height: 78px;
        background: rgba(235, 241, 255, 0.53);
        border: 1px solid #1890ff;
        border-radius: 50%;
        margin: 0;
        margin-left: 112px;
      }
    }
  }

  .btn-box {
    text-align: center;
    margin-top: 28px;
    :deep(.ant-btn) {
      border-color: #1890ff;
      background-color: #1890ff;
      width: 160px;
      margin-left: 130px;
    }
  }
}
</style>
